#/usr/bin/perl                                                                                                                           

%patterns;

for $sw ($ARGV[0]..$ARGV[1]){

    %patterns=();
    # Important = dead crypts have cloneId=-1, so include cloneId=-1 in patterns
    # the pattern of a dead crypt is wild type...
    # Try hashes of arrays to prevent memory explosions
    my @temp;
    for my $loc (0..243){
	$temp[$loc]=100;
    }
    # load up an array
    $patterns{-1}=[@temp];
    # Load all patterns in memory
    open (in,"sweep$sw/sweep$sw.patterns");
    while(<in>){
	chomp;
	@row=split(/\,/);
	# clone_id, locus 0..244, ms length = "pattern"	
	for my $loc (0..243){
	    # Add to an array
	    push @{ $patterns{$row[0]} }, $row[$loc+1]; 
	    #$patterns{$row[0]}{$loc}=$row[$loc+1];
	}
    }
    close in;

    my $day = 182; 
    my $generation;
    my $firstline=1;
    # Store ms pattern at each time step 
    %pathash=();
    %cidhash=();
    open (i1,"sweep$sw/sweep$sw.log");
    open (out, ">sweep$sw/sweep$sw.unique.clones.log");
    
    while(<i1>){
	chomp;
	@row=split(/\,/);
	if($firstline){
	    $generation=$row[3];
	    $firstline=0;
	}
	if($row[2]!=$day){	    
	    $sizeofpathash = keys(%pathash);
	    print out "$day,$sizeofpathash,$generation\n";
	    %pathash = ();
	    %cidhash = ();
	    # increase day
	    if($day==7280){
		$day=7300;
	    } else {
		$day+=182;
	    }
	    $generation=$row[3];
	} else {
	    # Add ms pattern to hash
	    $pat = "";
	    $cid = $row[1];
	    # ignore counting the dead clone pattern
	    if($cid!=-1){
		if(!defined($cidhash{$cid})){
		    $cidhash{$cid} = 1;
		    # go through microsats and add them to hash
		    for my $loc (0..243){
			$pat=$pat.$patterns{$cid}[$loc];
		    }
		    # Add pattern to hash
		    $pathash{$pat}=1;
		}
	    }
	}	
    }
    close i1;    

    # For day 7300
    $sizeofpathash = keys(%pathash);
    print out "$day,$sizeofpathash,$generation\n";
    close out;    
}

    
